go to previous page   go to home page   go to next page

Answer:

Button-click events are delivered to the actionPerformed() method, but it always does the same thing, regardless of which button is clicked.


Picture of the Problem

Somehow, we need to write actionPerformed() so that it does something different for each button. Look again at the method:

  public void actionPerformed( ActionEvent evt)
  {
    getContentPane().setBackground( Color.green );
    repaint();
  }

The picture shows the present situation. Event objects from both buttons are delivered to the same method, which changes the background to green no matter what event it receives.

red and green buttons

We would like the ActionEvent that is delivered to actionPerformed() to say what should be done. To do this, you can associate a different command with each button using

setActionCommand(String command)

Now each button sends its command (a String) as part of the ActionEvent when it is clicked. The actionPerformed() method uses the command to see what to do.

If you don't use setActionCommand() to assign a command string to a button, the command it sends when it is clicked will be the same as the words on the button. This is usually OK, but is awkward in large projects. You would like to be able to change the words on the buttons without changing the rest of the code.


QUESTION 10:

setActionCommand() is a member of what object(s)?